<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Schema;
use DB;

/* 登录成功通知任务 */

class UpInputJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data_input_job;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data_input_job)
    {
        $this->data_input_job = $data_input_job;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $data_input_job = $this->data_input_job;
        // info('UpInputJob');
        // info($data_input_job);
        $key_data = data_get($data_input_job,'key_data',[]);
        $sample_info_id = data_get($data_input_job,'sample_info_id',0);
        $arr = data_get($data_input_job,'arr',[]);
        $realname = data_get($data_input_job,'realname','');
        $oldInputs = DB::table('a_input_data')
                ->where('sample_info_id',$sample_info_id)
                ->select('id','val','testdata_key_id')
                ->get()->keyBy('testdata_key_id')->toArray();
        $inputLogs = [];
        $inputId = 0;
        foreach($key_data as $k => $v) {
            $v = (array)$v;
            $key_data_id = $v['id'];
            $value = $arr[$k];
            $oldInput = (array)data_get($oldInputs,$key_data_id,[]);
            if (!$oldInput) {
                //如果记录不存在，则插入
                $inputId = DB::table('a_input_data')->insertGetId(['sample_info_id' => $sample_info_id, 'testdata_key_id' => $key_data_id, 'val' => $value]);
            }else{
                if($oldInput['val'] != $value) {
                    $inputId = $oldInput['id'];
                    DB::table('a_input_data')->where('id', $inputId)->update(['val' => $value]);
                }
            }
            if($inputId){
                $inputLogs[] = [
                        'input_data_id'=>$inputId,
                        'manager_realname'=>$realname,
                        'val'=>$value,
                    ];
            }
            //因为有别的参数，所以这里判断下是否超了
            if(count($arr) === $k + 1) {
                break;
            }
        }
        if ($inputLogs) {
            DB::table('a_input_data_log')->insert($inputLogs);
        }
    }
}
